<template>
  <div class="demo">
    <div class="demo-title">上传前转换文件</div>
    <div class="demo-content">
      <Upload
        v-model:file-list="fileList"
        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
        :before-upload="beforeUpload"
      >
        <Button><UploadOutlined />Upload</Button>
      </Upload>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import Button from '@sscd/button';
  import Upload from '@sscd/upload';
  import type { UploadProps } from '@sscd/upload';
  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const img: HTMLImageElement = document.createElement('img');
        img.src = reader.result as string;
        img.onload = () => {
          const canvas = document.createElement('canvas');
          canvas.width = img.naturalWidth;
          canvas.height = img.naturalHeight;
          const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
          ctx.drawImage(img, 0, 0);
          ctx.fillStyle = 'red';
          ctx.textBaseline = 'middle';
          ctx.font = '33px Arial';
          ctx.fillText('Ant Design Vue', 20, 20);
          canvas.toBlob(resolve);
        };
      };
    });
  };
  const fileList = ref([]);
</script>
